package com.yl.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsV2Request;
import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class OssM3U8ToMp3Converter {
    private static final Logger log = LoggerFactory.getLogger(OssM3U8ToMp3Converter.class);

    /**
     * 根据前缀模糊查询文件 并且下载到指定路径下
     * @param prefix     列举根据前缀查询文件  现在最好是传频道名即文件夹名
     * @param newFileUrl 新文件地址  最好目标到文件夹下
     * @author : y
     * @date :  2024/7/12 22:24
     **/
    public static List<OSSObjectSummary> getAllFileNameByPrefix(String prefix, String newFileUrl) {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "zhishubucket-beijing";
        // 指定前缀，例如exampledir/object。
        String keyPrefix = "leaderVideoFile/" + prefix;
        List<OSSObjectSummary> list = new ArrayList<>();
        String newFilePath = newFileUrl + keyPrefix;
        File file = new File(newFilePath);
        if (!file.exists()) {
            log.info("文件夹不存在，需要创建");
            file.mkdirs();
        }
        // 设置最大个数。
        int maxKeys = 100;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, "LTAI5tGkRSpKDBCvb58N8bEc", "ZCwmNPYDJrAf6ChPkaf4WRcqauxaFX");
        try {
            String nextContinuationToken = null;
            ListObjectsV2Result result = null;
            // 分页列举指定前缀的文件。
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setPrefix(keyPrefix);
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);
                list = result.getObjectSummaries();
                for (OSSObjectSummary s : list) {
                    // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
                    // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
                    log.info("bucketName={},文件地址：{},新文件地址={}", bucketName, s.getKey(), (newFileUrl + s.getKey()));
                    ossClient.getObject(new GetObjectRequest(bucketName, s.getKey()), new File(newFileUrl + s.getKey()));
                }
                nextContinuationToken = result.getNextContinuationToken();
            } while (result.isTruncated());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            return list;
        }
    }

    public static void main(String[] args) throws Exception {
        List<OSSObjectSummary> nameByPrefix = getAllFileNameByPrefix("123456", "D:\\");
    }
}
